<?php

namespace app\controller\admin\sgz;

use app\model\admin\sgz\SgzBattle;
use app\model\admin\sgz\SgzBattleTeam;
use app\model\admin\sgz\SgzGenerals;
use app\model\admin\sgz\SgzWarMethods;
use app\model\admin\sgz\SgzWarMethodsGenerals;
use laytp\controller\Backend;
use laytp\library\CommonFun;
use think\facade\Db;

/**
 * Class Career
 * @package app\controller\admin\ah
 */
class Battle extends Backend
{
    protected $model;
    public $orderRule = ['id' => 'DESC'];

    public function initialize()
    {
        $this->model = new SgzBattle();
        parent::initialize(); // TODO: Change the autogenerated stub
    }

    public function index()
    {
        $resultName = [
            0 => '平局',
            1 => '胜利',
            2 => '失败',
        ];
        $where = $this->buildSearchParams();
        $order = $this->buildOrder();
        $allData = $this->request->param('all_data');
        $post = $this->request->param();
        if ($allData) {
            $data = $this->model->where($where)->order($order)->cache(true)->select()->toArray();
        } else {
            $limit = $this->request->param('limit', 10);
            if(isset($post['search_param']['team_code'])&&!empty($post['search_param']['team_code']['value'])){
                $ids = (new SgzBattleTeam())->where('team_code',$post['search_param']['team_code']['value'])->column("battle_id");
                $where[] = ['id','in',$ids];
            }
            $data = $this->model->with("battleGenerals")->where($where)->order($order)->paginate($limit)->toArray();
            $generals_id = [];
            foreach ($data['data'] as $item) {
                foreach ($item['battleGenerals'] as $it) {
                    $generals_id = array_merge($generals_id, explode(",", $it['team_code']));
                }
            }
            $generals = (new SgzGenerals())->whereIn('id', array_unique($generals_id))->column("name", "id");
            foreach ($data['data'] as &$item) {
                foreach ($item['battleGenerals'] as $key => $it) {
                    $item['teamGenerals' . $key] = [];
                    $item['teamGenerals' . $key][] = $generals[$it['master_generals_id']];
                    $item['teamGenerals' . $key][] = $generals[$it['one_generals_id']];
                    $item['teamGenerals' . $key][] = $generals[$it['two_generals_id']];
                    $item['teamResult' . $key] = $resultName[$it['result']];
                    $item['teamGenerals' . $key] = implode("|", $item['teamGenerals' . $key]);
                }
            }
        }
        return $this->success('数据获取成功', $data);
    }

    public function getBattleTeam()
    {
        $data = (new SgzBattleTeam())->cache(true)->hasWhere('battle')->group("team_code")->order('id desc')->select()->toArray();
        $ids = [];
        foreach ($data as $item){
            $ids[$item['master_generals_id']] = $item['master_generals_id'];
            $ids[$item['one_generals_id']] = $item['one_generals_id'];
            $ids[$item['two_generals_id']] = $item['two_generals_id'];
        }
        $generals = (new SgzGenerals())->whereIn('id',array_values($ids))->column("name","id");
        foreach ($data as &$item){
            $team_name = [];
            if(isset($generals[$item['master_generals_id']]))$team_name[] = $generals[$item['master_generals_id']];
            if(isset($generals[$item['one_generals_id']]))$team_name[] = $generals[$item['one_generals_id']];
            if(isset($generals[$item['two_generals_id']]))$team_name[] = $generals[$item['two_generals_id']];
            $item['team_name'] = implode("|",$team_name);
        }
        return $this->success('数据获取成功', $data);
    }


    //添加
    public function add()
    {
        $post = CommonFun::filterPostData($this->request->post());
        try {
            $result = $post['result0']+$post['result1'];
            if($result!=0&&$result!=3){
                return $this->error("比赛结果错误");
            }
            $data = [
                'season' => $post['season'],
                'imgs' => $post['imgs'],
                'create_time' => date("Y-m-d H:i:s"),
            ];
            Db::startTrans();
            $id = $this->model->insertGetId($data);
            $battleTeam = [];
            $team_code = [$post['master_generals_id0'], $post['one_generals_id0'], $post['two_generals_id0']];
            if (count(array_unique($team_code)) != 3) {
                return $this->error("阵容1里不能选择同一个武将");
            }
            sort($team_code);
            $new = [
                'master_generals_id' => $post['master_generals_id0'],
                'one_generals_id' => $post['one_generals_id0'],
                'two_generals_id' => $post['two_generals_id0'],
                'result' => $post['result0'],
                'battle_id' => $id,
                'create_time' => date("Y-m-d H:i:s"),
                'team_code' => implode(",", $team_code)
            ];
            array_push($battleTeam,$new);
            $team_code = [$post['master_generals_id1'], $post['one_generals_id1'], $post['two_generals_id1']];
            if (count(array_unique($team_code)) != 3) {
                return $this->error("阵容2里不能选择用同一个武将");
            }
            sort($team_code);
            $new = [
                'master_generals_id' => $post['master_generals_id1'],
                'one_generals_id' => $post['one_generals_id1'],
                'two_generals_id' => $post['two_generals_id1'],
                'result' => $post['result1'],
                'battle_id' => $id,
                'create_time' => date("Y-m-d H:i:s"),
                'team_code' => implode(",", $team_code)
            ];
            array_push($battleTeam,$new);
            if (count($battleTeam) > 0) (new SgzBattleTeam())->insertAll($battleTeam);
            Db::commit();
            $this->clearCache();
            return $this->success('添加成功', $post);
        } catch (\Exception $e) {
            return $this->exceptionError($e);
        }
    }

    //添加
    public function edit()
    {
        $post = CommonFun::filterPostData($this->request->post());
        try {
            $result = $post['result0']+$post['result1'];
            if($result!=0&&$result!=3){
                return $this->error("比赛结果错误");
            }
            Db::startTrans();
            $data = [
                'id' => $post['id'],
                'season' => $post['season'],
                'imgs' => $post['imgs'],
                'create_time' => date("Y-m-d H:i:s"),
            ];
            $this->model->update($data);
            $id = $post['id'];
            $battleTeam = [];
            $team_code = [$post['master_generals_id0'], $post['one_generals_id0'], $post['two_generals_id0']];
            if (count(array_unique($team_code)) != 3) {
                return $this->error("阵容1里不能选择同一个武将");
            }
            sort($team_code);
            if(empty($post['master_generals_id0'])||empty($post['one_generals_id0'])||empty($post['two_generals_id0'])){
                return $this->error("请选择阵容1武将");
            }
            $new = [
                'master_generals_id' => $post['master_generals_id0'],
                'one_generals_id' => $post['one_generals_id0'],
                'two_generals_id' => $post['two_generals_id0'],
                'result' => $post['result0'],
                'battle_id' => $id,
                'create_time' => date("Y-m-d H:i:s"),
                'team_code' => implode(",", $team_code)
            ];
            array_push($battleTeam,$new);
            $team_code = [$post['master_generals_id1'], $post['one_generals_id1'], $post['two_generals_id1']];
            if (count(array_unique($team_code)) != 3) {
                return $this->error("阵容2里不能选择用同一个武将");
            }
            sort($team_code);
            if(empty($post['master_generals_id1'])||empty($post['one_generals_id1'])||empty($post['two_generals_id1'])){
                return $this->error("请选择阵容2武将");
            }
            $new = [
                'master_generals_id' => $post['master_generals_id1'],
                'one_generals_id' => $post['one_generals_id1'],
                'two_generals_id' => $post['two_generals_id1'],
                'result' => $post['result1'],
                'battle_id' => $id,
                'create_time' => date("Y-m-d H:i:s"),
                'team_code' => implode(",", $team_code)
            ];
            array_push($battleTeam,$new);
            Db::name("sgz_battle_team")->where('battle_id',$id)->delete();
            if (count($battleTeam) > 0) (new SgzBattleTeam())->insertAll($battleTeam);
            Db::commit();
            $this->clearCache();
            return $this->success('添加成功', $post);
        } catch (\Exception $e) {
            return $this->exceptionError($e);
        }
    }

    //查看详情
    public function info()
    {
        $id = $this->request->param('id');
        $info = $this->model->find($id);
        if (is_object($info)) $info = $info->toArray();
        $list = (new SgzBattleTeam())->where('battle_id', $id)->field("*")->select()->toArray();
        $info['master_generals_id0'] = $list[0]['master_generals_id'];
        $info['one_generals_id0'] = $list[0]['one_generals_id'];
        $info['two_generals_id0'] = $list[0]['two_generals_id'];
        $info['result0'] = (string)$list[0]['result'];
        $info['master_generals_id1'] = $list[1]['master_generals_id'];
        $info['one_generals_id1'] = $list[1]['one_generals_id'];
        $info['two_generals_id1'] = $list[1]['two_generals_id'];
        $info['result1'] = (string)$list[1]['result'];
        return $this->success('获取成功', $info);
    }

    //设置展示
    public function setIsShow()
    {
        $id = $this->request->post('id');
        $fieldVal = $this->request->post('field_val');
        $isRecycle = $this->request->post('is_recycle');
        $update['is_show'] = $fieldVal;

        try {
            if ($isRecycle) {
                $updateRes = $this->model->onlyTrashed()->where('id', '=', $id)->update($update);
            } else {
                $updateRes = $this->model->where('id', '=', $id)->update($update);
            }

            if ($updateRes) {
                $this->clearCache();
                return $this->success('操作成功');
            } else if ($updateRes === 0) {
                return $this->success('未作修改');
            } else {
                return $this->error('操作失败');
            }
        } catch (\Exception $e) {
            return $this->exceptionError($e);
        }
    }

    public function getResult()
    {
        return $this->success('获取战法类型', [
            ['name' => '平局','value'=>0],
            ['name' => '胜利','value'=>1],
            ['name' => '失败','value'=>2],
        ]);
    }

    public function del()
    {
        $ids = array_filter($this->request->post('ids'));
        if (!$ids) {
            return $this->error('参数ids不能为空');
        }
        try{
            Db::startTrans();
            if ($this->model->destroy($ids)) {
                Db::name("sgz_battle_team")->whereIn("battle_id",$ids)->delete();
                Db::commit();
                $this->clearCache();
                return $this->success('数据删除成功');
            } else {
                return $this->error('数据删除失败');
            }
        }catch (\Exception $e){
            return $this->exceptionError($e);
        }
    }
}